package net.nshc.kwkim.mycalc.buttonlistener;

import net.nshc.kwkim.mycalc.*;
import net.nshc.kwkim.mycalc.activity.*;
import android.app.*;
import android.content.*;
import android.util.*;
import android.view.*;
import android.widget.*;

public class BracketButtonClickListener extends ButtonClickListener {
	private int value = 0;
	public BracketButtonClickListener(Context context, int value) {
		super(context);
		this.editTextInput = (EditText)((Activity)context).findViewById(R.id.input);
		this.value = value;
	}

	public void onClick(View v) {
		StringBuilder temp = new StringBuilder(editTextInput.getText().toString());
		int LBracket= 0, RBracket = 0;
		boolean isDigit = false;
		LBracket = countLBracket(temp);
		RBracket = countRBracket(temp);
		isDigit = isDigit(temp);
		if(MyCalcActivity.bLog)Log.d("Block_log", "isDigit = "+isDigit);
		if(value == 1 && !isDigit){
			temp.append("(");
		}else if((value == 0 && isDigit) && (temp != null) && (LBracket > RBracket)){
			temp.append(")");
		}
		editTextInput.setText(temp);
	}

	private int countLBracket(StringBuilder temp){
		int Lcount = 0;
		for(int i = 0; i < temp.length(); i++){
			if(temp.charAt(i) == '('){
				Lcount++;
			}
		}
		return Lcount;
	}

	private int countRBracket(StringBuilder temp){
		int Rcount = 0;
		for(int i = 0; i < temp.length(); i++){
			if(temp.charAt(i) == ')'){
				Rcount++;
			}
		}
		return Rcount;
	}

	private boolean isDigit(StringBuilder temp){
		Character c;
		if(temp.length() != 0){
			c = temp.charAt(temp.length()-1);
			if (( c == '1') || ( c == '2') || ( c == '3') || ( c == '4') || ( c == '5') || 
					( c == '6') || ( c == '7') || ( c == '8') || ( c == '9') || ( c == '0') || ( c == ')')) 
				return true;
		}

		return false;
	}
}
